using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Trigger2D : MonoBehaviour
{
    public bool m_IsTrigger = false;
    public LayerMask m_TriggerMaskLayer;
    public HashSet<Collider2D> m_Collider2Ds = new HashSet<Collider2D>();

    public UnityEvent m_OnEnterTrigger = new UnityEvent();
    public UnityEvent m_OnExitTrigger = new UnityEvent();

    public UnityEvent<Collider2D> m_OnEnterTriggerWithCollider = new UnityEvent<Collider2D>();
    public UnityEvent<Collider2D> m_OnExitTriggerWithCollider = new UnityEvent<Collider2D>();

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (GameCheckUtils.CheckLayer(m_TriggerMaskLayer,collision.gameObject))
        {
            m_OnEnterTriggerWithCollider?.Invoke(collision);

            m_Collider2Ds.Add(collision);
            if (!m_IsTrigger && m_Collider2Ds.Count > 0)
            {
                m_IsTrigger = true;
                m_OnEnterTrigger?.Invoke();
            }
        }
        
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (GameCheckUtils.CheckLayer(m_TriggerMaskLayer, collision.gameObject))
        {
            m_OnExitTriggerWithCollider?.Invoke(collision);

            m_Collider2Ds.Remove(collision);
            if (m_IsTrigger && m_Collider2Ds.Count == 0)
            {
                m_IsTrigger = false;
                m_OnExitTrigger?.Invoke();
            }
        }
    }
}
